package com.woniuxy.joylife.manager.exception;

import com.woniuxy.common.enums.JoyLifeHttpState;
import com.woniuxy.joylife.manager.utils.R;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.Map;

@RestControllerAdvice(basePackages = "com.woniuxy.joylife.manager.controller")
public class ManagerExceptionControllerAdvice {

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public R handleValidate(MethodArgumentNotValidException e){
        BindingResult bindingResult = e.getBindingResult();
        Map<String, String> errosMap = new HashMap<>();
        bindingResult.getFieldErrors().forEach(fieldError -> {
            errosMap.put(fieldError.getField(),fieldError.getDefaultMessage());
        });
        System.out.println(errosMap);
        return R.error(JoyLifeHttpState.VALIDATE_EXCEPTION.getCode()
                ,JoyLifeHttpState.VALIDATE_EXCEPTION.getMsg()).put("data",errosMap);
    }

    @ExceptionHandler(Exception.class)
    public R handleBaseException(Exception e){
        return R.error(JoyLifeHttpState.BASE_EXCEPTION.getCode()
                ,JoyLifeHttpState.BASE_EXCEPTION.getMsg()).put("data",e.getMessage());
    }
}
